//
//  SJRegister2ViewController.m
//  WSL
//
//  Created by CJ on 2017/12/12.
//  Copyright © 2017年 sanjuetech. All rights reserved.
//

#import "SJRegister2ViewController.h"
#import "SJRegisterApi.h"

@interface SJRegister2ViewController ()

@property (nonatomic, strong) UIScrollView *containView;
@property (nonatomic, strong) UITextField *nameField;
@property (nonatomic, strong) UITextField *passwordField;
@property (nonatomic, strong) UIButton *loginButton;
@property (nonatomic, strong) UIButton *backButton;

@end

@implementation SJRegister2ViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [SJStatisticTool beginLogPageView:NSStringFromClass([self class])];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    
    [SJStatisticTool endLogPageView:NSStringFromClass([self class])];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self setupUI];
}

- (void)setupUI {
    
    [self.view addSubview:self.containView];
    self.containView.sd_layout.spaceToSuperView(UIEdgeInsetsZero);
    
    UIImageView *phoneBG = [UIImageView new];
    phoneBG.image = [UIImage imageNamed:@"signin_bg_input_phonenumber"];
    [self.containView addSubview:phoneBG];
    phoneBG.sd_layout
    .centerXEqualToView(self.containView)
    .topSpaceToView(self.containView, SJLayoutFrame(190))
    .widthIs(SJLayoutFrame(248))
    .heightIs(SJLayoutFrame(32));
    
    [self.containView addSubview:self.nameField];
    self.nameField.sd_layout
    .centerXEqualToView(self.containView)
    .topSpaceToView(self.containView, SJLayoutFrame(190))
    .widthIs(SJLayoutFrame(231))
    .heightIs(SJLayoutFrame(32));
    
    UIImageView *passwordBG = [UIImageView new];
    passwordBG.image = [UIImage imageNamed:@"signin_bg_input_phonenumber"];
    [self.containView addSubview:passwordBG];
    passwordBG.sd_layout
    .centerXEqualToView(self.containView)
    .topSpaceToView(phoneBG, SJLayoutFrame(30))
    .widthIs(SJLayoutFrame(248))
    .heightIs(SJLayoutFrame(32));
    
    [self.containView addSubview:self.passwordField];
    self.passwordField.sd_layout
    .centerXEqualToView(self.containView)
    .topSpaceToView(phoneBG, SJLayoutFrame(30))
    .widthIs(SJLayoutFrame(231))
    .heightIs(SJLayoutFrame(32));
    
    [self.containView addSubview:self.loginButton];
    self.loginButton.sd_layout
    .centerXEqualToView(self.containView)
    .topSpaceToView(passwordBG, SJLayoutFrame(67))
    .widthIs(SJLayoutFrame(263))
    .heightIs(SJLayoutFrame(55));
    
    
    // scrollview自动contentsize
    [self.containView setupAutoContentSizeWithBottomView:self.loginButton bottomMargin:0];
    
    // 返回
    [self.view addSubview:self.backButton];
    self.backButton.sd_layout
    .topSpaceToView(self.view, SJLayoutFrame(8))
    .leftSpaceToView(self.view, SJLayoutFrame(10))
    .heightIs(SJLayoutFrame(27))
    .widthIs(SJLayoutFrame(27));
    
}

#pragma mark - gerter

- (UIButton *)backButton {
    
    if (!_backButton) {
        
        _backButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_backButton setImage:[UIImage imageNamed:@"btn_back"] forState:UIControlStateNormal];
        [_backButton addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
        
    }
    return _backButton;
}


- (void)backAction {
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (UIScrollView *)containView {
    
    if (!_containView) {
        
        _containView = [UIScrollView new];
        
        UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(singleTapAction)];
        singleTap.cancelsTouchesInView = NO;
        [_containView addGestureRecognizer:singleTap];
        
    }
    return _containView;
}

- (void)singleTapAction {
    
    [self.view endEditing:YES];
}


- (UIButton *)loginButton{
    
    if (!_loginButton) {
        
        _loginButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_loginButton addTarget:self action:@selector(loginAction) forControlEvents:UIControlEventTouchUpInside];
        [_loginButton setImage:[UIImage imageNamed:@"signin_btn_signin"] forState:UIControlStateNormal];
        
    }
    return _loginButton;
}

- (void)loginAction {
    
    if (self.passwordField.text.length < 6) {
        NSString *msg = @"密码至少6位";
        [SVProgressHUD showErrorWithStatus:msg];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
        });
        return;
    }
    
    // 1.拼接参数
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"nickname"] = self.nameField.text;
    parameters[@"pwd"] = [self.passwordField.text md5String];
    parameters[@"repwd"] = [self.passwordField.text md5String];
    parameters[@"phone"] = self.phoneStr;
    parameters[@"sms"] = self.smsStr;
    
    SJRegisterApi *api = [[SJRegisterApi alloc] initWithParameters:parameters];
    [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        
        if ([api.responseObject[@"result"][@"err"] intValue] == 0) {
            
            [SJUserDefaults setObject:api.responseObject[@"content"][@"token"] forKey:SJToken];
            [SJUserDefaults setObject:api.responseObject[@"content"] forKey:SJUserInfo];
            [SJUserDefaults synchronize];
            
            [self dismissViewControllerAnimated:YES completion:nil];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [[NSNotificationCenter defaultCenter] postNotificationName:SJDidLoginNotification object:nil];
            });
        } else {
            
            NSString *msg = api.responseObject[@"result"][@"msg"];
            [SVProgressHUD showErrorWithStatus:msg];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [SVProgressHUD dismiss];
            });
        }
        
    } failure:^(YTKBaseRequest *request) {
        
    }];
}


- (UITextField *)nameField{
    
    if (!_nameField) {
        
        _nameField = [UITextField new];
        _nameField.returnKeyType = UIReturnKeyNext;
        _nameField.clearButtonMode = UITextFieldViewModeWhileEditing;
        _nameField.textColor = SJColorHexString(@"#ffffff");
        _nameField.font = [UIFont systemFontOfSize:SJLayoutFrame(15)];
        
        // 改变
        //        [_pwPhoneField addTarget:self action:@selector(pwPhoneEditingChanged) forControlEvents:UIControlEventEditingChanged];
        
        NSString *holderText = @"设置昵称";
        NSMutableAttributedString *placeholder = [[NSMutableAttributedString alloc]initWithString:holderText];
        [placeholder addAttribute:NSForegroundColorAttributeName
                            value:SJColorHexString(@"#ffffff90")
                            range:NSMakeRange(0, holderText.length)];
        [placeholder addAttribute:NSFontAttributeName
                            value:[UIFont systemFontOfSize:SJLayoutFrame(15)]
                            range:NSMakeRange(0, holderText.length)];
        _nameField.attributedPlaceholder = placeholder;
        
    }
    return _nameField;
}


- (UITextField *)passwordField{
    
    if (!_passwordField) {
        
        _passwordField = [UITextField new];
        _passwordField.returnKeyType = UIReturnKeyDone;
        _passwordField.secureTextEntry = YES;
        _passwordField.clearButtonMode = UITextFieldViewModeWhileEditing;
        _passwordField.textColor = SJColorHexString(@"#ffffff");
        _passwordField.font = [UIFont systemFontOfSize:SJLayoutFrame(15)];
        _passwordField.enablesReturnKeyAutomatically = YES;
        
        // 改变
        //        [_pwPasswordField addTarget:self action:@selector(pwPasswordEditingChanged) forControlEvents:UIControlEventEditingChanged];
        //        // 按回车
        //        [_pwPasswordField addTarget:self action:@selector(pwPasswordDidEndOnExit) forControlEvents:UIControlEventEditingDidEndOnExit];
        
        NSString *holderText = @"设置密码";
        NSMutableAttributedString *placeholder = [[NSMutableAttributedString alloc]initWithString:holderText];
        [placeholder addAttribute:NSForegroundColorAttributeName
                            value:SJColorHexString(@"#ffffff90")
                            range:NSMakeRange(0, holderText.length)];
        [placeholder addAttribute:NSFontAttributeName
                            value:[UIFont systemFontOfSize:SJLayoutFrame(15)]
                            range:NSMakeRange(0, holderText.length)];
        _passwordField.attributedPlaceholder = placeholder;
        
    }
    return _passwordField;
}


@end

